package com.droiddata;

import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class SQLiteTransactionTemplate {
	private ISQLiteTransactionManager transactionManager;

	public SQLiteTransactionTemplate(
			ISQLiteTransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}

	public <T> T execute(ITransactionCallback<T> action)
			throws TransactionException {
		SQLiteDatabase db = transactionManager.beginTransaction();
		T result = null;
		try {			
			result = action.doInTransaction(db, transactionManager.getTransactionStatus());
		} catch (RuntimeException ex) {
			rollbackOnException(ex);
			throw ex;
		} catch (Error err) {
			rollbackOnException(err);
			throw err;
		} finally {
			transactionManager.endTransaction();
		}

		return result;
	}

	private void rollbackOnException(Error err) {
		Log.e("SQLiteTransactionTemplate",
				"Rolling back transaction because of an unchecked error.");
	}

	private void rollbackOnException(RuntimeException ex) {
		Log.e("SQLiteTransactionTemplate",
				"Rolling back transaction because of an unchecked exception.");
	}
}
